package org.ichow.scenegame.model
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.SWFLoader;
	import com.greensock.loading.XMLLoader;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import org.ichow.debug.Log;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	/**
	 * ...
	 * 素材代理
	 * 负责素材加载
	 * @author M.ichow
	 */
	public class AssetsProxy extends Proxy
	{
		public static const NAME : String = "AssetsProxy";
		public static const ASSETS_COMPLETE : String = "configComplete";
		
		private var _xml : XML;
		private var _skin : SWFLoader;
		private var _path : String;
		private var _xmlURL : String = "assets/xml/config.xml";
		private var _skinURL : String = "assets/swf/skin.swf";
		
		public function AssetsProxy( path : String = "" )
		{
			super( NAME , null );
			_path = path;
		}
		
		override public function onRegister() : void
		{
			super.onRegister();
			var l : XMLLoader = new XMLLoader( _path + _xmlURL , { name: "config" , onComplete: onXMLComplete , onFail: onXMLFail } );
			l.load( true );
		}
		
		/**
		 * 加载失败
		 * @param	e
		 */
		private function onXMLFail( e : LoaderEvent ) : void
		{
			Log.trace( "加载失败：" + e.toString() );
		}
		
		/**
		 * 加载xml成功
		 * @param	e
		 */
		private function onXMLComplete( e : LoaderEvent ) : void
		{
			_xml = new XML( LoaderMax.getContent( "config" ) );
			_skin = new SWFLoader( _path + _skinURL , { name: "skin" , onComplete: onSkinComplete } );
			_skin.load( true );
			Log.trace( "配置加载完成" );
		}
		
		/**
		 * 素材加载完成
		 * @param	e
		 */
		private function onSkinComplete( e : LoaderEvent ) : void
		{
			Log.trace( "素材加载完成" );
			sendNotification( ASSETS_COMPLETE );
		}
		
		/**
		 * 获取类
		 * @param	v
		 * @return
		 */
		public function getClass( v : String = null ) : Class
		{
			return _skin.getClass( v );
		}
		
		/**
		 * 获取素材文件的舞台对象
		 * @param	v
		 * @return
		 */
		public function getSkin( v : String = null ) : DisplayObject
		{
			//trace( v + ": " + _skin.getSWFChild( v ).width );
			return _skin.getSWFChild( v );
		}
		
		/**
		 * 获取场景列表[XML]
		 * @return
		 */
		public function getItems() : XML
		{
			return new XML( _xml.items );
		}
		
		/**
		 * 获取配置
		 * @param	v
		 * @return
		 */
		public function getConfig( v : String = null ) : String
		{
			if ( !v || !_xml )
				return null;
			return _xml.config[ v ];
		}
		
		/**
		 * 获取动画地址
		 * @param	v
		 * @return
		 */
		public function getURL( v : String ) : String
		{
			var url : String = _xml.items.@[ v ];
			if ( !url )
			{
				for ( var i : int = 0 , len : int = _xml..item.length() ; i < len ; i++ )
				{
					if ( v == _xml..item[ i ].@title )
					{
						url = _xml..item[ i ].@url;
						return url;
					}
				}
			}
			return url;
		}
	
	}

}